package ldh.im.dto.codec.binery;

import io.netty.buffer.ByteBuf;
import ldh.im.dto.codec.BaseImCoder;
import ldh.im.dto.base.Req;
import ldh.im.util.LocalDateTimeUtil;

public abstract class AckToCodec<T extends Req> extends BaseImCoder<T> {

    @Override
    public void encode(T ackTo, ByteBuf byteBuf) {
        checkEncode(ackTo);
        if (ackTo.getCreateDateTime() == null) {
            byteBuf.writeLong(0L);
        } else {
            byteBuf.writeLong(LocalDateTimeUtil.getTime(ackTo.getCreateDateTime()));
        }
//        byteBuf.writeLong(ackTo.getLocalSeq());
        writeString(byteBuf, ackTo.getLocalSeq());
    }

    @Override
    public void decode(T ackTo, ByteBuf byteBuf) {
        long time = byteBuf.readLong();
        if (time != 0L) {
            ackTo.setCreateDateTime(LocalDateTimeUtil.create(time));
        }
        ackTo.setLocalSeq(readString(byteBuf));
    }

    protected void checkEncode(T ackTo) {
        if (ackTo.getLocalSeq() == null) {
            throw new RuntimeException("请设置LocalSeq值！");
        }
    }
}
